﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Net;
using FJASPX.Framwork.Helper;
using FJASPX.Framwork.Config;

namespace FJASPX.UI.Extention
{
    //任何问题联系 author :vipwan@sina.com  各种图片输出handler 
    //如果输出错误,或者图片不存在. 需要在在web.config中配置默认输出图片路径.DefaultImagePath
    //

    /// <summary>
    ///输出手机号码和电话号码以及电子邮件等字符型的图片 ...axd?s=*******
    /// </summary>
    public class StringOutImage : IHttpHandler
    {
        /// <summary>
        /// You will need to configure this handler in the web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpHandler Members

        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse respose = context.Response;

            string unicodeStr = request.QueryString["s"];

            if (string.IsNullOrEmpty(unicodeStr)) { respose.End(); return; }

            string phone = StringHelper.ToString(unicodeStr);
            //画图
            CreateStringImage(respose, null, phone);

        }

        #endregion

        public static void CreateImage(HttpResponse response, string sourceFile, string text)
        {
            HttpContext.Current.Response.Clear();
            try
            {
                response.ContentType = "image/jpeg";
                //原图
                Bitmap sImage = string.IsNullOrEmpty(sourceFile) ? new Bitmap(100, 30) : new Bitmap(sourceFile);

                //验证码图
                Bitmap wImage = new Bitmap(100, 30, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                Graphics wg = Graphics.FromImage(wImage);
                wg.Clear(Color.White);
                wg.DrawString(text, new Font("Verdana", 18), new SolidBrush(Color.DarkBlue), 0, 0);
                wg.Save();

                //make Graphics.
                Graphics g = Graphics.FromImage(sImage);
                int x; //临时变量
                int y; //监时变量    
                int w = 100; //验证图的宽度
                int h = 30; //验证图的高度
                int al; //alpha
                int rl; //Red
                int gl; //Green
                int bl; //Blue

                //开始绘图
                for (x = 1; x < w; x++)
                {
                    for (y = 1; y < h; y++)
                    {
                        al = wImage.GetPixel(x, y).A;
                        rl = wImage.GetPixel(x, y).R;
                        gl = wImage.GetPixel(x, y).G;
                        bl = wImage.GetPixel(x, y).B;
                        al = 70;

                        if (rl - 50 > 0)
                            rl -= 50;
                        if (gl - 50 > 0)
                            gl -= 50;
                        if (bl - 50 > 0)
                            bl -= 50;
                        g.DrawEllipse(new Pen(new SolidBrush(Color.FromArgb(al, rl, gl, bl))), x, y, 1, 1);
                    }
                }
                g.Save();
                sImage.Save(response.OutputStream, ImageFormat.Jpeg);
                wg.Dispose();
                g.Dispose();
                sImage.Dispose();
                wImage.Dispose();
            }
            catch (Exception e)
            {
                response.Write(e.Message);
            }
        }

        public static void CreateStringImage(HttpResponse response, string sourceFile, string text)
        {
            HttpContext.Current.Response.Clear();
            response.ContentType = "image/jpeg";
            int ww = 11 * text.Length;
            Bitmap map = new Bitmap(ww, 20);
            Graphics gx = Graphics.FromImage(map);
            gx.Clear(Color.White);
            gx.DrawString(text, new Font("Verdana", 12), new SolidBrush(Color.Black), 0, 1);
            gx.Save();

            map.Save(response.OutputStream, ImageFormat.Jpeg);
            map.Dispose();
            gx.Dispose();
        }
    }

    /// <summary>
    /// Common.Web.CookieHelp.Get("valid",false)不获取Cookie
    /// 输出随机生成的验证图片.axd?len=4&r=0.12324343 参数使用随机防止图片不更新. 
    /// </summary>
    public class ValidOutImage : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse respose = context.Response;

            int length = int.Parse(string.IsNullOrEmpty(request.QueryString[0]) ? "4" : request.QueryString[0]);
            if (length > 6)
                length = 6;//验证码禁止大于6个字符.

            string text = Guid.NewGuid().ToString().ToUpperInvariant().Substring(0, length);

            //Common.Web.CookieHelp.Set("valid", text);//设置Cookie这样才能验证.

            StringOutImage.CreateImage(respose, null, text);
        }

        #endregion
    }


    /// <summary>
    /// 创建缩略图输出.必须参数:图片路径,输出图片宽度,输出图片高度.长度宽度如果小于原图,将输出原图.
    /// </summary>
    public class CreateMiniImage : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;

            string path = HttpUtility.UrlDecode(request.QueryString["path"]);
            string w = request.QueryString["w"];
            string h = request.QueryString["h"];
            string t = request.QueryString["t"];//裁剪类型.

            ImageHelp.ImageOutPutType type = ImageHelp.ImageOutPutType.HW;
            if (!string.IsNullOrEmpty(t))
            {
                t = t.ToLowerInvariant();
                switch (t)
                {
                    case "hw":
                        type = ImageHelp.ImageOutPutType.HW;
                        break;
                    case "cut":
                        type = ImageHelp.ImageOutPutType.CUT;
                        break;
                    case "h":
                        type = ImageHelp.ImageOutPutType.H;
                        break;
                    case "w":
                        type = ImageHelp.ImageOutPutType.W;
                        break;
                    default:
                        break;
                }
            }
            if (!String.IsNullOrEmpty(path))
            {
                path = path.Substring(path.IndexOf(".com") + 1);
            }
            if (!File.Exists(HttpContext.Current.Server.MapPath(path)))
            {
                //throw new Exception("缩略图原图未找到."); 
                using (Image img = Image.FromFile(HttpContext.Current.Server.MapPath(
                    ConfigBase.GetConfig("DefaultImagePath", true))))
                {
                    img.Save(response.OutputStream, ImageFormat.Jpeg);
                    response.End();
                    return;
                }
            }

            using (Image img = Image.FromFile(HttpContext.Current.Server.MapPath(path)))
            {
                using (Image mini =
                    ImageHelp.CreateMini(img, int.Parse(h), int.Parse(w), type))
                {
                    mini.Save(response.OutputStream, ImageFormat.Jpeg);
                    response.End();
                    return;
                }
            }
        }
    }

    /// <summary>
    /// 禁止站外盗链接的图片输出Module
    /// </summary>
    public class ImageOutModule : IHttpModule
    {

        #region IHttpModule Members

        public void Dispose()
        {
            //throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
#if !DEBUG
            
#endif
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpResponse response = HttpContext.Current.Response;
            HttpRequest request = HttpContext.Current.Request;

            string imagePath = request.PhysicalPath;

            if (imagePath != null && (
                imagePath.ToLower().EndsWith(".jpg") ||
                imagePath.ToLower().EndsWith(".jpeg") ||
                imagePath.ToLower().EndsWith(".png")))
            {
                if (!File.Exists(imagePath))
                {
                    using (Image img = Image.FromFile(HttpContext.Current.Server.MapPath(
                            ConfigBase.GetConfig("DefaultImagePath", true))))
                    {
                        img.Save(response.OutputStream, ImageFormat.Jpeg);
                        response.End();
                        return;
                    }

                }
                else if (request.RawUrl.ToLower().Contains(
                     ConfigBase.GetConfig("Domain", true).
                    Replace("http://", "").Replace("https://", "")))
                {
                    using (Image img = Image.FromFile(HttpContext.Current.Server.MapPath(
                          ConfigBase.GetConfig("DefaultImagePath", true))))
                    {
                        img.Save(response.OutputStream, ImageFormat.Jpeg);
                        response.End();
                        return;
                    }
                }

            }
        }

        #endregion
    }

    /// <summary>
    /// 首页图片新闻裁剪图片.
    /// </summary>
    public class PhotoNewsImage : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            var request = context.Request;
            var response = context.Response;

            response.Clear();

            string newsId = request.QueryString["newsid"];//新闻id
            uint h = uint.Parse(request.QueryString["h"]);//图片高度
            uint w = uint.Parse(request.QueryString["w"]);//图片宽度
            //获取图片内容
            string newsContent = ""; //BLL.NewsBusiness.NewsGet(new Guid(newsId)).NewsContent;
            //临时变量.图片路径
            string imagePath = "";
            //正则表达式
            Regex regImg = new Regex(@"src\=.+?\.(jpg|gif|png|bmp|jpeg)", RegexOptions.IgnoreCase);

            //开始得到匹配集合.
            var mathes = regImg.Matches(newsContent);



            foreach (Match math in mathes)
            {
                string tmpStr;

                //排斥非本地图片
                if (math.Value.ToLowerInvariant().Contains("http://") ||
                    math.Value.ToLowerInvariant().Contains("ftp://") ||
                    math.Value.ToLowerInvariant().Contains("https://"))
                    continue;
                //得到纯净路径
                tmpStr = math.Value.ToLowerInvariant().Replace("src=\"", "").Replace("src='", "").Replace("src=", "");
                //满足条件开始跳出循环
                if (File.Exists(HttpContext.Current.Server.MapPath(tmpStr)))
                {
                    using (Image img = Image.FromFile(HttpContext.Current.Server.MapPath(tmpStr)))
                    {
                        if (img.Height < h || img.Width < w)
                        {
                            continue;
                        }

                        imagePath = tmpStr;
                        break;
                    }
                }
            }
            //创建输出图片.
            using (Image outPutImage = ImageHelp.CreateMini(
                    Image.FromFile(
                    HttpContext.Current.Server.MapPath
                    (
                    imagePath == "" ? ConfigBase.GetConfig("DefaultImagePath") : imagePath)
                    ),
                    (int)h,
                    (int)w,
                    ImageHelp.ImageOutPutType.HW))
            {
                outPutImage.Save(response.OutputStream, ImageFormat.Jpeg);
                response.End();
            }
        }

        #endregion
    }

    public class GetUriImg : IHttpHandler
    {

        /// </summary>
        /// <param name="url">图片的URL</param>
        /// <param name="ProxyServer">代理服务器</param>
        /// <returns>图片内容</returns>
        public byte[] GetFile(string url, string proxyServer)
        {
            WebResponse rsp = null;
            byte[] retBytes = null;
            try
            {
                Uri uri = new Uri(url);
                WebRequest req = WebRequest.Create(uri);
                rsp = req.GetResponse();
                Stream stream = rsp.GetResponseStream();
                if (!string.IsNullOrEmpty(proxyServer))
                {
                    req.Proxy = new WebProxy(proxyServer);
                }
                using (MemoryStream ms = new MemoryStream())
                {
                    int b;
                    while ((b = stream.ReadByte()) != -1)
                    {
                        ms.WriteByte((byte)b);
                    }
                    retBytes = ms.ToArray();
                }
            }
            catch (Exception ex)
            {
                retBytes = null;
            }
            finally
            {
                if (rsp != null)
                {
                    rsp.Close();
                }
            }
            return retBytes;
        }

        #region IHttpHandler 成员

        public bool IsReusable
        {
            get { throw new NotImplementedException(); }
        }

        public void ProcessRequest(HttpContext context)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}